package scparser;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

import Camera.Camera;
import lib.common.Constants;
import model.Image;
import model.Light;
import model.Shader;
import model.primitive.Primitive;
import raycast.Scene;
import scparser.factory.primitiveFactory.PrimitiveFactoryException;
import scparser.factory.sceneFactory.SceneAbstractFactory;
import scparser.factory.sceneFactory.SceneCameraFactory;
import scparser.factory.sceneFactory.SceneImageFactory;
import scparser.factory.sceneFactory.SceneLightFactory;
import scparser.factory.sceneFactory.SceneObjectFactory;
import scparser.factory.sceneFactory.SceneShaderFactory;

public class Parser {
	private static Parser instance;
	
	public static Parser instance() {
		if (instance == null) {
			instance = new Parser();
		}
		
		return instance;
	}
	
	public Scene parse (String fileName)  {
		File sceneFile = new File(fileName);
		String line;
		BufferedReader br = null;
		Scene scene = new Scene();
		SceneAbstractFactory sceneFactory;
		
		try {
			br = new BufferedReader(new FileReader(sceneFile));
			while ((line = br.readLine()) != null) {
				line = line.trim();
				
				if (line.startsWith(Constants.type.object.toString())) {
					sceneFactory =  new SceneObjectFactory(scene);
					scene.addPrimitive((Primitive) sceneFactory.create(br));
				} else if (line.startsWith(Constants.type.shader.toString())) {
					sceneFactory = new SceneShaderFactory(scene);
					scene.addShader((Shader) sceneFactory.create(br));
				} else if (line.startsWith(Constants.type.camera.toString())) {
					sceneFactory = new SceneCameraFactory(scene);
					scene.setCamera((Camera)sceneFactory.create(br));
				} else if (line.startsWith(Constants.type.image.toString())) {
					sceneFactory = new SceneImageFactory(scene);
					/*scene.setImage((Image)sceneFactory.create(br));*/
				} else if (line.startsWith(Constants.type.light.toString())) {
					sceneFactory = new SceneLightFactory(scene);
					scene.addLight((Light) sceneFactory.create(br));
				}				
			}
		} catch (IOException e) {
			e.printStackTrace();
		} catch (PrimitiveFactoryException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				br.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		return scene;
	}
}
